package com.sieaf.web;

import java.io.IOException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionRedirect;
import org.apache.struts.actions.DispatchAction;
import com.sieaf.Constants.Constant;
import com.sieaf.config.ConstantValue;
import com.sieaf.exception.AppException;

public class BaseDispatchAction extends DispatchAction {
	
	/**
	 * ��Ϣ����1
	 * 
	 * @param messages
	 * @param msgKey
	 */

	protected void addActionMsg(ActionMessages messages, String msgKey) {
		messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(msgKey));
	}

	/**
	 * ��Ϣ����2
	 * 
	 * @param messages
	 * @param msgKey
	 * @param msgObj
	 */
	protected void addActionMsg(ActionMessages messages, String msgKey,
			Object msgObj) {
		messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(msgKey,
				msgObj));
	}
	/**
	 * ȡ��������HttpSession�е�Object
	 * 
	 * @param request
	 * @param id
	 * @return
	 */
	protected Object getSessionValue(HttpServletRequest request, String id) {
		HttpSession session = request.getSession(true);
		return session.getAttribute(id);
	}

	/**
	 * ���ƶ��Ķ��󱣴浽HttpSession��
	 * 
	 * @param request
	 * @param id
	 * @param valueObj
	 */
	protected void setSessionValue(HttpServletRequest request, String id,
			Object valueObj) {
		HttpSession session = request.getSession(true);
		session.setAttribute(id, valueObj);
	}

	/**
	 * ��HttpSession��ɾ���ƶ��Ķ���
	 * 
	 * @param request
	 * @param id
	 */
	protected void removeSessionValue(HttpServletRequest request, String id) {
		HttpSession session = request.getSession(true);
		Object value = session.getAttribute(id);

		if (value != null) {
			session.removeAttribute(id);
		}
	}

	public ActionRedirect CreateActionRedirect(ActionForward action, Map map) {
		ActionRedirect re = new ActionRedirect(action);
		Iterator it = map.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry ety = (Map.Entry) it.next();
			Object obj = ety.getValue();
			if (obj instanceof String)
				re.addParameter(ety.getKey().toString(), obj.toString());
		}

		return re;
	}

	public Map PutRequestToMap(HttpServletRequest request) {
		try {
			String contentType = request.getHeader("Content-type");
			Map map=null;
			if (null != contentType && contentType.startsWith("multipart/"))
				map= PutFileRequestToMap_(request);
			else
				map= PutRequestToMap_(request);
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	//added by kevin,for save default value for paging.
	public Map putRequestToMapPaging(HttpServletRequest request) {
		String contentType = request.getHeader("Content-type");
		Map map=null;
		try {
			if (null != contentType && contentType.startsWith("multipart/"))
				map= PutFileRequestToMap_(request);
			else
				map= PutRequestToMap_(request);
			if(map.get("_p_row_size")==null)
				map.put("_p_row_size", "10");
			if(map.get("_p_title_size")==null)
				map.put("_p_title_size", "5");
			if(map.get("_p_page")==null)
				map.put("_p_page", "1");
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	/* ���ļ�ѡ���ͱ?�ύ */
	public Map PutFileRequestToMap_(HttpServletRequest request)
			throws Exception {
		DiskFileUpload fu = new DiskFileUpload();
		List fileItems = fu.parseRequest(request);
		HashMap map = new HashMap();
		Iterator i = fileItems.iterator();
		while (i.hasNext()) {
			FileItem fi = (FileItem) i.next();
			if (fi.isFormField()) {
				map.put(fi.getFieldName(), fi.getString("utf-8"));
			} else {
				map.put(fi.getFieldName(), fi);
			}
		}
		return map;
	}

	/* ��ͨ�ͱ?�ύ */
	public Map PutRequestToMap_(HttpServletRequest request) throws Exception {
		Map map = request.getParameterMap();
		Map map2 = new HashMap();
		Iterator it = map.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry ety = (Map.Entry) it.next();
			String sKey = ety.getKey().toString();
			if ("method".equals(sKey))
				continue;
			String[] sVal = (String[]) ety.getValue();
			if (sVal.length == 1) {
				map2.put(sKey, sVal[0]);
			} else
				map2.put(sKey, sVal);
		}
		return map2;
	}

	public Map AjaxPutRequestToMap(HttpServletRequest request) {
		Map map = request.getParameterMap();
		Map map2 = new HashMap();
		Iterator it = map.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry ety = (Map.Entry) it.next();
			String sKey = ety.getKey().toString();
			if ("method".equals(sKey))
				continue;
			String[] sVal = (String[]) ety.getValue();
			if (sVal.length == 1) {
				map2.put(sKey,toChinese(sVal[0]));
			} else
				map2.put(sKey, sVal);
		}
		return map2;
	}

	public Map PutRequestAttributeToMap(HttpServletRequest request) {
		Enumeration enu = request.getAttributeNames();
		HashMap mp = new HashMap();
		while (enu.hasMoreElements()) {
			Object obj = enu.nextElement();
			if (obj instanceof String) {
				String key = (String) enu.nextElement();
				mp.put(key, request.getAttribute(key));
			}
		}
		return mp;
	}

	public void SaveAppException(HttpServletRequest request, AppException e) {
		request.setAttribute("org.lenovo.global.message",e.getClientDesc());
	}

	public void SaveMessage(HttpServletRequest request, String s) {
//		request.getSession().setAttribute("org.cibsd.global.message", s);
		request.setAttribute("alertMsg", s);
	}

	public void PageProcess(HttpServletRequest request, HashMap map) {
		request.setAttribute("_p_page", map.get("_p_page"));
		request.setAttribute("_p_size", map.get("_p_size"));
		request.setAttribute("_p_total_count", map.get("_p_total_count"));
		request.setAttribute("_p_total_page", map.get("_p_total_page"));
		request.setAttribute("_p_action", request.getRequestURI());
	}

	public void savePagingParameters(HttpServletRequest request, HashMap Map) {
		request.setAttribute("_p_total", Map.get("_p_total"));
		request.setAttribute("_p_title_size", "5");

	}

	public void AjaxProcess(HttpServletResponse response, ArrayList lists)
			throws Exception {
		response.setHeader("Cache-Control", "no-store");
		response.setDateHeader("Expires", 0);
		response.setContentType("text/xml; charset=GB2312");
		org.w3c.dom.Document document = javax.xml.parsers.DocumentBuilderFactory
				.newInstance().newDocumentBuilder().newDocument();
		org.w3c.dom.Element root = document.createElement("root");
		int size = (lists == null ? 0 : lists.size());
		for (int i = 0; i < size; i++) {
			Map mdp = (Map) lists.get(i);
			org.w3c.dom.Element row = document.createElement("row");
			Iterator it = mdp.entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry ety = (Map.Entry) it.next();
				String key = ety.getKey().toString();
				String value = ety.getValue()==null?"":ety.getValue().toString();
				row.setAttribute(key, value);
				root.appendChild(row);
			}
		}
		document.appendChild(root);
		javax.xml.transform.dom.DOMSource doms = new javax.xml.transform.dom.DOMSource(
				document);
		javax.xml.transform.stream.StreamResult sr = new javax.xml.transform.stream.StreamResult(
				response.getOutputStream());
		javax.xml.transform.TransformerFactory tf = javax.xml.transform.TransformerFactory
				.newInstance();
		javax.xml.transform.Transformer t = tf.newTransformer();
		t.setOutputProperty("encoding", "GB2312");
		t.transform(doms, sr);
	}

	public ActionForward redirectEncode(String url,HashMap hm) {
		ActionRedirect redirect = new ActionRedirect(url);
		redirect.addParameter("_p_row_size", "10");
		redirect.addParameter("_p_title_size", "5");
		redirect.addParameter("_p_page", "1");
		Iterator it = hm.entrySet().iterator();
		try{
		    while (it.hasNext()) {
		      Map.Entry entry = (Map.Entry) it.next();
		      String key = (String)entry.getKey();
		      Object value = entry.getValue();
		      boolean bl=value instanceof String; 
		      if(bl)
		      redirect.addParameter(key,URLEncoder.encode(value.toString()));
		    }
		    redirect.addParameter(Constant.FLAG_ENCODER,"1");
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return redirect;
	}
	public ActionForward redirectNotEncode(String url,HashMap hm) {
		ActionRedirect redirect = new ActionRedirect(url);
		redirect.addParameter("_p_row_size", "10");
		redirect.addParameter("_p_title_size", "5");
		redirect.addParameter("_p_page", "1");
		Iterator it = hm.entrySet().iterator();
		try{
		    while (it.hasNext()) {
		      Map.Entry entry = (Map.Entry) it.next();
		      String key = (String)entry.getKey();
		      Object value = entry.getValue();
		      boolean bl=value instanceof String; 
		      if(bl)
		      redirect.addParameter(key,value.toString());
		    }
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return redirect;
	}
	
	public ActionForward redirect(String url) {
		ActionRedirect redirect = new ActionRedirect(url);
		redirect.addParameter("_p_row_size", "10");
		redirect.addParameter("_p_title_size", "5");
		redirect.addParameter("_p_page", "1");
		return redirect;
	}
	
	  private String toChinese(final String pOriginalString){
		    if (pOriginalString == null) {
		      return null;
		    }
		    if (isChinese(pOriginalString)) {
		      return pOriginalString;
		    }
		    try {
		      return new String(pOriginalString.getBytes("8859_1"), "gb2312");
		    }
		    catch (Exception ex) {
		      ex.printStackTrace();
		    }
		    return null;
		  }
	  
	  private boolean isChinese(String pValue){
		    for(int i=0; i<pValue.length(); i++){
		      if ((int)pValue.charAt(i) > 256)
		        return true;
		    }
		    return false;
		  }
	  
	public static void main(String[] args)
	{ try{
		//new BaseDispatchAction().BaseLogin(null,null);
		}catch(Exception e){}
	}
}
